package org.example;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

import static org.example.sendJsonPostRequest.AES_KEY128;

public class AES_ECB {
    // 固定密钥（必须是16、24或32字节长度，对应AES-128、AES-192、AES-256）
//    private static final String SECRET_KEY = "123abcABC";

    // 加密算法/模式/填充
    private static final String ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * AES ECB模式加密
     * @param plainText 明文
     * @return Base64编码的密文
     */
    public static String encrypt(String plainText) throws Exception {
        // 确定需要的字节长度
        int byteLength = 16; // 128->16, 192->24, 256->32

        // 将密码转换为字节数组
        byte[] keyBytes = AES_KEY128.getBytes(StandardCharsets.UTF_8);

        // 创建目标字节数组并补零
        byte[] finalKey = new byte[byteLength];
        System.arraycopy(keyBytes, 0, finalKey, 0, Math.min(keyBytes.length, finalKey.length));

        // 创建密钥规范
        SecretKeySpec secretKey = new SecretKeySpec(finalKey, "AES");

        // 获取加密实例并初始化
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        // 执行加密
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));

        // 返回Base64编码的密文
//        return Base64.getEncoder().encodeToString(encryptedBytes);
        // 返回十六进制字符串
        return bytesToHex(encryptedBytes);  // 结果为"7d6e116e0d2c2d17938b12f61a14c708"
    }

    /**
     * AES ECB模式解密
     * @param encryptedText Base64编码的密文
     * @return 解密后的明文
     */
    public static String decrypt(String encryptedText) throws Exception {
        // 确定需要的字节长度
        int byteLength = 16; // 128->16, 192->24, 256->32

        // 将密码转换为字节数组
        byte[] keyBytes = AES_KEY128.getBytes(StandardCharsets.UTF_8);

        // 创建目标字节数组并补零
        byte[] finalKey = new byte[byteLength];
        System.arraycopy(keyBytes, 0, finalKey, 0, Math.min(keyBytes.length, finalKey.length));

        // 创建密钥规范
        SecretKeySpec secretKey = new SecretKeySpec(finalKey, "AES");

        // 获取解密实例并初始化
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        // Base64解码并执行解密
//        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));

        byte[] decrypted1 = hex2byte(encryptedText);
        byte[] decryptedBytes = cipher.doFinal(decrypted1);

        // 返回解密后的字符串
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();

    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int i = 0; i < bytes.length; i++) {
            int v = bytes[i] & 0xFF;
            hexChars[i * 2] = HEX_ARRAY[v >>> 4];
            hexChars[i * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars);
    }

    private static byte[] hex2byte(String strhex) {
        if (strhex == null)
            return null;

        int l = strhex.length();
        if (l % 2 == 1)
            return null;

        byte[] b = new byte[l / 2];
        for (int i = 0; i != l / 2; ++i)
            b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16);

        return b;
    }

}
